package server.proxy;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Vector;


/**
 * This class manages all the request times asked by the clients of this proxy server.
 * 
 * @author Maxim
 *
 */
public class RequestCounter {

    private Map<String, Vector<Long>> _clientsRequests;
    
    
    public RequestCounter (){
    	
		this._clientsRequests = new ConcurrentHashMap<String, Vector<Long>>();
		
    }
    
    public void addRequest(String clientIP, long requestTime){
    	
    	if(this._clientsRequests.get(clientIP) != null)
    		this._clientsRequests.get(clientIP).add(requestTime);
    	
    	else{
    		Vector<Long> tReguestList = new Vector<Long>();
    		tReguestList.add(requestTime);
    		this._clientsRequests.put(clientIP, tReguestList);
    	}
    }
    
    public boolean canSendMoreRequest(String clientIP){
    	
    	if (this._clientsRequests.get(clientIP) == null)
    		return true;
    	
    	int tRequestListSize = this._clientsRequests.get(clientIP).size();
    	
    	if( tRequestListSize < Config.REQUEST_NUMBER)
    		return true;
    	
    	else{
    		 long tFirstRequestTime = this._clientsRequests.get(clientIP).get(tRequestListSize - Config.REQUEST_NUMBER );
    		 long tLastRequestTime = this._clientsRequests.get(clientIP).get(tRequestListSize - 1);
    		 
    		 
    		 if( convertMillisecondsToMinutes(tLastRequestTime - tFirstRequestTime) < Config.MINUTES){
    			
    			this._clientsRequests.get(clientIP).clear();
    			return false; 
    		 }
    		 else
    		 {
    			 Vector<Long> tmp = deleteRedundantRequestsTime(this._clientsRequests.get(clientIP), tRequestListSize - Config.REQUEST_NUMBER);
    			 this._clientsRequests.put(clientIP, tmp);
    			 return true;
    		 }
    	}
    }
    
    private Vector<Long> deleteRedundantRequestsTime(Vector<Long> oldRequestsTimes, int newRequestTimeIndex){
    	
    	Vector<Long> tAnswer = new Vector<Long>();
    	
    	int tOldVectorSize = oldRequestsTimes.size();
    	
    	for(int j = newRequestTimeIndex; j < tOldVectorSize; j++)
    		tAnswer.add(oldRequestsTimes.get(j));
    	
    	
    	return tAnswer;
    }
    
    private int convertMillisecondsToMinutes(Long milliseconds){
    	return (int) ((milliseconds / 1000) / 60);
    }
    
    
	
    
    
	
}
